import { message, Table } from "antd";
import { forEach, find, findIndex, map } from "lodash";
import { useState, useEffect, useRef } from "react";

import ColorPicker from "../ColorPicker/index";
import Remove from "../Remove";

import { useAnalysisTask } from "~/components/Visualization/store/useTaskState";
import { getChartParamStatistics } from "~/hooks/Visualization/use-visualization-api";
import { AggregationQuery, AggregationType } from "~/modules/api-server/types";
import { ChartItem } from "~/modules/workspace/models";
import { useWorkSpace } from "~/modules/workspace/store/use-workspace";
import eventBus from "~/utils/event";

interface Props {
  chartName: string;
  chartIndex: number;
  isMerge: boolean;
}

const AggrType: string[] = ["AVG", "MAX", "MIN", "STD", "MEAN"];

const ChartParamsList = (props: Props, ref: any) => {
  const paramsListColumns = [
    {
      title: "颜色",
      dataIndex: "color",
      key: "color",
      width: 150,
      render: (row: any, record: any) => (
        <div
          style={{
            width: "125px",
          }}
        >
          <ColorPicker
            color={record.color}
            change={(e: any) => onColorChange(e, record)}
          />
        </div>
      ),
    },
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
      width: 170,
      textWrap: "word-break",
      ellipsis: true,
    },
    {
      title: "最大值",
      dataIndex: "MAX",
      key: "MAX",
    },
    {
      title: "最小值",
      dataIndex: "MIN",
      key: "MIN",
    },
    {
      title: "平均值",
      dataIndex: "AVG",
      key: "AVG",
    },
    {
      title: "标准差",
      dataIndex: "STD",
      key: "STD",
    },
    {
      title: "中位数",
      dataIndex: "MEAN",
      key: "MEAN",
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      render: (row: any, record: any) => (
        <a onClick={() => onDelParam(row, record)}>删除</a>
      ),
    },
  ];
  // 获取task信息
  const { analysisTask } = useAnalysisTask();
  //获取工作区图表配置
  const { workSpace, update } = useWorkSpace();
  const removeRef = useRef();
  const [paramsListData, setParamsListData] = useState<any[]>([]);
  const paramsListRef = useRef(paramsListData);
  paramsListRef.current = paramsListData;
  const [statistics, setStatistics] = useState<AggregationQuery>({
    startTime: "",
    endTime: "",
    tailNo: "",
    params: [],
    aggregationTypes: [
      AggregationType.Max,
      AggregationType.Min,
      AggregationType.Avg,
      AggregationType.Std,
      AggregationType.Mean,
    ],
  });
  useEffect(() => {
    eventBus.on(`chartParamsStatistics`, async (value: any) => {
      statistics.startTime = value.startTime;
      statistics.endTime = value.endTime;
      setStatistics(statistics);
      getStatisticsData();
    });
    return () => {
      clearInterval(timer);
    };
  }, []);

  // 选择的图表
  let timer: any = null;
  const stopInterval = () => {
    timer && clearInterval(timer);
    timer = null;
  };
  let num: number = 0;
  const { load }: any = getChartParamStatistics(statistics);
  const getStatisticsData = (value?: any) => {
    stopInterval();
    num = 0;
    timer = setInterval(async () => {
      num += 1;
      const { data } = await load();
      if (!data) {
        message.error("统计值获取失败！");
        stopInterval();
      }
      if (data?.paramAggregation?.processStatus === "COMPLETED") {
        stopInterval();
        handleParamAggregation(data, value);
      } else if (
        num >= 24 ||
        data?.paramAggregation?.processStatus === "FAILED"
      ) {
        clearInterval(timer);
      }
    }, 5000);
  };

  useEffect(() => {
    getTableData();
    clearInterval(timer);
    return () => {
      clearInterval(timer);
    };
  }, [props]);

  const handleParamAggregation = (
    data: { paramAggregation: { result: any } },
    value: any
  ) => {
    const paramStatistics = data?.paramAggregation.result;
    if (paramStatistics.length > 0) {
      const TableData: any = value ? [...value] : [...paramsListRef.current];
      forEach(TableData, (m, index) => {
        const mAggr = find(paramStatistics, (n) => {
          if (m.paramType === "Field") {
            return n.param.expr === m.title;
          } else {
            return n.param.expr === m.expression;
          }
        });
        for (const aggrName of AggrType) {
          m[aggrName] = find(mAggr.param.values, (t) => {
            return t.aggregationType === aggrName;
          })?.value;
        }
      });
      setParamsListData(TableData);
    }
  };

  //   选择颜色
  const onColorChange = (color: string, chart: any) => {
    forEach(workSpace.splitCharts, (item: any, index: number) => {
      if (item.name === props.chartName && index === props.chartIndex) {
        forEach(item.data, (it: any, i: number) => {
          if (it.title === chart.name) {
            it.color = color;
          }
        });
      }
    });
    update(workSpace);
  };
  //删除参数
  const [delText, setDelText] = useState<string>("");
  const [delParam, setDelparam] = useState<string>("");
  const onDelParam = (v: any, record: any) => {
    setDelText(`是否删除参数 ${record.name} ？`);
    setDelparam(record.name);
    removeRef.current && (removeRef.current as any).onDelete();
  };
  const onDelChartParam = () => {
    let delParamNum: number = 0;
    let delChartNum: number = 0;
    forEach(workSpace.splitCharts, (item: any, index: number) => {
      if (item.name === props.chartName && index === props.chartIndex) {
        delChartNum = index;
        delParamNum = findIndex(item.data, (it: any) => {
          return it.title === delParam;
        });
      }
    });
    workSpace.splitCharts[delChartNum].data.splice(delParamNum, 1);
    update(workSpace);
  };

  const getTableData = () => {
    if (props.chartName !== "数据表") {
      const chart: any = find(
        workSpace.splitCharts,
        (item: ChartItem, index: number) => {
          return item.name === props.chartName && index === props.chartIndex;
        }
      );
      const chartParams: any = [];
      const tableData: any[] = map(chart?.data, (item, index) => {
        return {
          ...item,
          key: index,
          name: item.title,
          MIN: "计算中...",
          MAX: "计算中...",
          AVG: "计算中...",
          STD: "计算中...",
          MEAN: "计算中...",
        };
      });
      setParamsListData(tableData);

      if (tableData.length > 0) {
        forEach(tableData, (m) => {
          chartParams.push({
            type: m.paramType,
            expr: m.paramType === "Custom" ? m.expression : m.title,
          });
        });
        statistics.params = chartParams;
        statistics.tailNo = analysisTask.tailno;
        setStatistics(statistics);
        getStatisticsData(tableData);
      }
    }
  };

  return (
    <>
      <Table
        rowKey={(record) => {
          return record.key + Date.now();
        }}
        columns={paramsListColumns}
        pagination={{}}
        dataSource={paramsListData}
        size="small"
      />
      <Remove ref={removeRef} delText={delText} onDelTask={onDelChartParam} />
    </>
  );
};

export default ChartParamsList;
